package cn.rulian.base.basis.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.rulian.base.basis.bo.SortManager;
import cn.rulian.base.basis.service.SortManagerService;
import cn.rulian.base.basis.vo.SortVo;
import cn.rulian.base.common.dto.Message;
import cn.rulian.base.common.util.SpringUtil;
import cn.rulian.base.common.util.xx;
import cn.rulian.base.common.vo.Result;

/**
 * 公共类型
 */

@Controller
@RequestMapping("/base/basis/sort")
public class SortController {
	
	@Autowired
	private SortManagerService sortManagerService;
	
	private final String path="base/basis/sort_"; //页面基本路径

	/**
	 * 页面基本路径
	 */
	private String getPath()
	{
		return path;
	}
	
	/**
	 * 列表页面
	 */
	@RequestMapping("/listPage")
	public String listPage(Model model,String key) 
	{
		try {
			//计算是否拥有‘排序号’属性
			SortManager manager = sortManagerService.findFirstByKey(key);
			boolean havaOrderNum = xx.haveField(Class.forName(manager.getBoName()), "orderNum");
			model.addAttribute("havaOrderNum", havaOrderNum); //是否拥有‘排序号’属性
		} catch (ClassNotFoundException e) {
		}
		
		model.addAttribute("key", key);
		return this.getPath()+"list";
	}
	
	/**
	 * 列表页面（只查看页面）
	 */
	@RequestMapping("/listViewPage")
	public String listViewPage(Model model,String key) 
	{
		try {
			//计算是否拥有‘排序号’属性
			SortManager manager = sortManagerService.findFirstByKey(key);
			boolean havaOrderNum = xx.haveField(Class.forName(manager.getBoName()), "orderNum");
			model.addAttribute("havaOrderNum", havaOrderNum); //是否拥有‘排序号’属性
		} catch (ClassNotFoundException e) {
		}
		
		model.addAttribute("key", key);
		return this.getPath()+"listView";
	}

	/**
	 * 查询
	 * @throws Exception 
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/listData")
	@ResponseBody
	public Result listData(SortVo vo) throws Exception {
		 //获取manager
		String key = vo.getKey();
		SortManager manager = sortManagerService.findFirstByKey(key);
        
        //获取dao
        JpaRepository dao = (JpaRepository) SpringUtil.getBean(Class.forName(manager.getDaoName()));
        
        //查询
		Sort sort = null; 
        if(xx.haveField(Class.forName(manager.getBoName()), "orderNum")) //检测是否拥有orderNum属性
		{
			sort = new Sort(Direction.ASC, "orderNum"); //排序号排序
		}
		else
		{
			sort = new Sort(Direction.ASC, "code"); //编号排序
		}
       
		Pageable pageable = new PageRequest(vo.getPage()-1,vo.getRows(),sort); //分页查询条件
        Page<Object> page = dao.findAll(pageable);
        
		return Result.getResult(page);
	}


	/**
	 * 增加页面
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/addPage")
	public String addPage(Model model,String key) {
		
		//自动计算下一排序号
		int nextNum = 0;
		try {
			//计算是否拥有‘排序号’属性
			SortManager manager = sortManagerService.findFirstByKey(key);
			JpaRepository dao = (JpaRepository) SpringUtil.getBean(Class.forName(manager.getDaoName()));
			boolean havaOrderNum = xx.haveField(Class.forName(manager.getBoName()), "orderNum");
			model.addAttribute("havaOrderNum", havaOrderNum); //是否拥有‘排序号’属性
			
			if(havaOrderNum) 
			{
				List ls = dao.findAll();
				for(Object obj: ls)
				{
					Integer num = (Integer)xx.getFieldValue(obj, "orderNum");
					if(num != null && num.intValue() > nextNum)
					{
						nextNum = num.intValue();
					}
				}

				nextNum++;
				model.addAttribute("nextNum", nextNum); 
			}
			
			
		} catch (Exception e) {
		}
		model.addAttribute("key", key); 
		return this.getPath()+"add";
	}

	/**
	 * 增加
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/add")
	@ResponseBody
	public Message add(SortVo vo) {
		Message rm = new Message();
		try {
			//获取manager
			String key = vo.getKey();	
			SortManager manager = sortManagerService.findFirstByKey(key);
			
			//构建bo
			Class boClass =  Class.forName(manager.getBoName()); 
			Object bo = boClass.newInstance();
			xx.setValue(bo, "code", vo.getCode());
			xx.setValue(bo, "name", vo.getName());
			xx.setValue(bo, "remark", vo.getRemark());
			xx.setValue(bo, "orderNum", vo.getOrderNum());

	        //获取dao,并保存
	        JpaRepository dao = (JpaRepository) SpringUtil.getBean(Class.forName(manager.getDaoName()));
	        dao.save(bo);
	        
			rm.setMsg("保存成功！");
			rm.setCode(Message._SUCCESS);
		} catch (Exception e) {
			rm.setMsg("保存失败，异常信息：<br/>" + e.toString());
			rm.setCode(Message._ERROR);
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 修改页面
	 * @throws ClassNotFoundException 
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/updatePage")
	public String updatePage(Model model, Long id,String key) throws ClassNotFoundException {
		
		//查询bo
		SortManager manager = sortManagerService.findFirstByKey(key);
        JpaRepository dao = (JpaRepository) SpringUtil.getBean(Class.forName(manager.getDaoName()));
		boolean havaOrderNum = xx.haveField(Class.forName(manager.getBoName()), "orderNum");
		model.addAttribute("havaOrderNum", havaOrderNum); //是否拥有‘排序号’属性
		
        Object bo = dao.findOne(id);
        //传值
		model.addAttribute("bo", bo);
		model.addAttribute("key", key);
		
		return this.getPath()+"update";
	}

	/**
	 * 修改
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/update")
	@ResponseBody
	public Message update(SortVo vo,Long id,String key) {
		Message rm = new Message();
		try {
			//获取manager
			SortManager manager = sortManagerService.findFirstByKey(key);
	        JpaRepository dao = (JpaRepository) SpringUtil.getBean(Class.forName(manager.getDaoName()));
	        
	        //更新值
	        Object bo = dao.findOne(id);
	        xx.setValue(bo, "code", vo.getCode());
			xx.setValue(bo, "name", vo.getName());
			xx.setValue(bo, "remark", vo.getRemark());
			xx.setValue(bo, "orderNum", vo.getOrderNum());
			dao.save(bo);
			
			rm.setMsg("保存成功！");
			rm.setCode(Message._SUCCESS);
		} catch (Exception e) {
			rm.setMsg("保存失败，异常信息：<br/>" + e.toString());
			rm.setCode(Message._ERROR);
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 删除
	 * @throws ClassNotFoundException 
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/delete")
	@ResponseBody
	public Message delete(Long ids[], String key) throws ClassNotFoundException {
		Message rm = new Message();
		SortManager manager = sortManagerService.findFirstByKey(key);
        JpaRepository dao = (JpaRepository) SpringUtil.getBean(Class.forName(manager.getDaoName()));
		try {
			for(Long id:ids)
			{
				dao.delete(id);
			}
			
			rm.setMsg("删除成功！");
			rm.setCode(Message._SUCCESS);
		} catch (Exception e) {
			rm.setMsg("删除失败！！！<br/><br/>原因：该信息已被其使用，不能删除！" );
			rm.setCode(Message._ERROR);
			e.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * 详情页面
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/detailPage")
	public String detailPage(Model model, Long id,String key) {
		try {
			//获取manager
			SortManager manager = sortManagerService.findFirstByKey(key);
	        JpaRepository dao = (JpaRepository) SpringUtil.getBean(Class.forName(manager.getDaoName()));
	        
	        Object bo = dao.findOne(id);
	        model.addAttribute("bo", bo);
			
		} catch (Exception e) {
		}
		
		return this.getPath()+"detail";
	}
	
	/**
	 * 根据类型Key查询，主要供页面下拉框取数据用
	 * @throws ClassNotFoundException 
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/findAll")
	@ResponseBody
	public List findAll(String key) throws  Exception
	{
		SortManager manager = sortManagerService.findFirstByKey(key);
        JpaRepository dao = (JpaRepository) SpringUtil.getBean(Class.forName(manager.getDaoName()));
		Sort sort = null;
		if(xx.haveField(Class.forName(manager.getBoName()), "orderNum")) //检测是否拥有orderNum属性
		{
			sort = new Sort(Direction.ASC, "orderNum"); //排序号排序
		}
		else
		{
			sort = new Sort(Direction.ASC, "code"); //编号排序
		}
		return dao.findAll(sort);
	}

}
